<?php

namespace app\controller\api;

use app\base\BaseEncryptController;
use app\libs\Oss;
use app\libs\Util;
use app\model\activity\LeadershipRecModel;
use app\model\goods\GoodsModel;
use app\model\goods\GoodsNavbarModel;
use app\model\goods\GoodsTypeModel;
use app\model\goods\HotKeywordModel;
use app\model\store\StoreBannerModel;
use app\model\store\StoreModel;
use app\model\system\BannerModel;
use app\model\user\UserProtocolModel;
use think\Request;


/**
 * 小程序首页请求接口
 * Class Index
 * @package app\controller
 */
class Index extends BaseEncryptController
{
    protected function initialize()
    {
        parent::initialize();
    }

    /**
     * 小程序api-首页列表
     * @param int $type
     * @param int $pagenow
     * @param int $limit
     * @param string $location
     * @param string $store_id
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function apiGetPage($type = 0, $pagenow = 1, $limit = 10, $location = "", $store_id = '')
    {
        $GoodsModel = new GoodsModel();
        $goodsField = "a.id as goods_id,a.goods_title,a.goods_img,a.goods_min_price,a.goods_min_market_price,a.goods_max_price,a.goods_up_count,a.goods_share_count,a.goods_collect_count,a.goods_read_count,a.goods_sale,a.goods_storage,a.goods_tag";
        //全部
        $map = [
            'a.goods_hot_status' => 2,
            'a.goods_status' => 1,
            'c.status' => 0
        ];
        //判断是否是认证商家
        $data = $GoodsModel
            ->alias('a')
            ->storeId($store_id)
            ->leftJoin("t_goods_type c", "a.goods_type_id=c.id")
            ->leftJoin("t_store s", "a.store_id=s.id")
            ->where($map)->order('a.sort desc,a.id desc')->field($goodsField)->limit(($pagenow - 1) * $limit, $limit)->select();
        $out_data = json_decode(json_encode($data), true);
        $rsps['list'] = array_merge($out_data);
        return self::returnMsg(1, $rsps);
    }

    /**
     * 获取首页数据
     * @param int $type
     * @param int $type_id
     * @param int $level
     * @param int $pagenow
     * @param int $limit
     * @param string $store_id
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getList($type = 0, $type_id = 0, $level = 2, $pagenow = 1, $limit = 10, $store_id = "")
    {
        $GoodsModel = new GoodsModel();
        $goodsField = "a.id as goods_id,a.goods_title,a.goods_img,a.goods_min_price,a.goods_min_unit,a.goods_min_market_price,a.goods_max_price,a.goods_up_count,a.goods_share_count,a.goods_collect_count,a.goods_read_count,a.goods_sale,a.goods_storage,a.goods_tag,s.id,s.store_name,s.store_label";
        //全部
        $map = [
            'a.goods_hot_status' => 2,
            'a.goods_status' => 1,
            'a.goods_special' => 0,
            'c.status' => 0
        ];
        if (!empty($type)) {
            $map['a.goods_nav_id'] = $type;
        }
        $type_ids = [];
        if (!empty($type_id)) {
            $type_ids = GoodsTypeModel::getChildId($type_id);
        }
        //判断是否是认证商家
        $data = $GoodsModel
            ->alias('a')
            ->storeId($store_id)
            ->goodsType($type_ids)
            ->leftJoin("t_goods_type c", "a.goods_type_id=c.id")
            ->leftJoin("t_store s", "a.store_id=s.id")
            ->where($map)
            ->order('a.sort asc,a.id asc')
            ->field($goodsField)
            ->limit(($pagenow - 1) * $limit, $limit)
            ->select();
        $out_data = json_decode(json_encode($data), true);
        foreach ($out_data as &$value) {
            if (mb_strpos($value['goods_tag'], " ") > 0) {
                $value['goods_tag'] = mb_substr($value['goods_tag'], 0, mb_strpos($value['goods_tag'], " "));
            }
        }
        $rsps['list'] = array_merge($out_data);
        return self::returnMsg(1, $rsps);
    }

    /**
     * 分类信息
     * @param string $type
     * @param string $store_id
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getTypePage($type = 'goods', $store_id = '')
    {
        $field = "id,name,img,parent_id,sort";
        $map = [
            'status' => 0
        ];
        $out_list = [];
        switch ($type) {
            case 'goods':
                $goodsModel = new GoodsModel();
                $class_model = new GoodsTypeModel();
                $data = $class_model->where($map)->field($field)->select();
                $list = Util::levelTreeChildren($data, 0);
                Util::listOrder($list, 'sort', 'desc', 'number');
                $listIds = Util::getChildrenIds($list);
                $out_list = [];
                foreach ($listIds as $key => $value) {
                    $map_temp = [
                        'goods_status' => 1,
                        'whereIn' => [
                            'field' => 'goods_type_id',
                            'condition' => $value['ids_str'],
                        ]
                    ];
                    $res = $goodsModel->getListCommonIn($map_temp, "id DESC", 1000, 'id,goods_title,goods_img,goods_min_price,goods_max_price', $store_id, $this->currentUser['user_id']);
                    if (empty($store_id)) {
                        if (count($res) > 0) {
                            $out_list[$key]['goodslist'] = $res;
                            $out_list[$key]['title'] = $value['title'];
                        }
                    } else {
                        if (count($res) > 0) {
                            $item = [
                                'goodslist' => $res,
                                'title' => $value['title']
                            ];
                            $out_list[] = $item;
                        }
                    }
                }
                break;
        }
        return self::returnMsg(1, $out_list);
    }

    /**
     * banner 列表获取
     * @param string $area
     * @return string
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getBannerPage($area = 'index')
    {
        $field = 'id,banner_title,banner_src,jump_type,jump_link,goods_id,start_time,end_time';
        $order = 'rank desc';
        $time = time();
        $banner_model = new BannerModel();
        $data = $banner_model->where('status', 1)
            ->where('area', $area)
            ->where('start_time', '<', $time)
            ->where('end_time', '>', $time)->order($order)->field($field)->select();
        if (count($data) == 0) {
            //            $data[] = [
            //                'banner_src' => "http://yinjia.oss-cn-beijing.aliyuncs.com/banner/20200425080936_2bzr.jpg",
            //                'banner_title' => "活动就是大家",
            //                'goods_id' => 0,
            //                'area' => '',
            //                'id' => 0,
            //                'jump_link' => "",
            //                'jump_type' => 1
            //            ];
        }
        return self::returnMsg(1, $data);
    }

    /**
     * 店铺banner
     * @param string $id
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getStoreBannerPage($id = '')
    {
        $field = 'id,banner_title,banner_src,jump_type,jump_link,goods_id,start_time,end_time';
        $order = 'rank desc';
        $time = time();
        $banner_model = new StoreBannerModel();
        $data = $banner_model
            ->where('store_id', $id)
            ->where('status', 1)
            ->where('start_time', '<=', $time)
            ->where('end_time', '>=', $time)->order($order)->field($field)->select();
        $out_data['banner'] = $data;
        $store_model = new StoreModel();
        $basic = $store_model->getInfo($id, "store_name,store_type,store_label,is_own_shop,store_desc,store_scope,real_name,create_time,store_deposit");

        StoreModel::formatx($basic);
        $basic['real_name'] = mb_substr($basic['real_name'], 0, 1) . ((mb_strlen($basic['real_name'])) > 2 ? '**' : '*');
        $out_data['basic'] = $basic;
        return self::returnMsg(1, $out_data);
    }

    /**
     * banner 详情
     * @param string $id
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getBannerDetail($id = '')
    {
        $banner_model = new BannerModel();
        $banner = $banner_model->getInfo($id);
        if (empty($banner)) {
            return self::returnMsg(0);
        }
        if (!empty($banner['banner_detail'])) {
            $banner['banner_detail'] = explode(',', $banner['banner_detail']);
        } else {
            $banner['banner_detail'] = [];
        }
        return self::returnMsg(1, $banner);
    }

    /**
     * 店铺banner 详情
     * @param string $id
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getStoreBannerDetail($id = '')
    {
        $banner_model = new StoreBannerModel();
        $banner = $banner_model->getInfo($id, 'banner_detail');
        if (empty($banner)) {
            return self::returnMsg(0);
        }
        if (!empty($banner['banner_detail'])) {
            $banner['banner_detail'] = explode(',', $banner['banner_detail']);
        } else {
            $banner['banner_detail'] = [];
        }
        return self::returnMsg(1, $banner['banner_detail']);
    }

    /**
     * 热门搜索词
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getHotKeyword()
    {
        $HotKeywordModel = new HotKeywordModel();
        $map['type'] = 1;
        $map['status'] = 1;
        $res = $HotKeywordModel->where($map)->limit(10)->order("shearch_count desc,id desc")->field("keyword")->select();
        return self::returnMsg(1, $res);
    }

    /**
     * 商品搜索
     * @param Request $request
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function onGoodsSearch(Request $request)
    {
        $formData = $request->param();
        $goods_model = new GoodsModel();
        //"a.store_id,a.goods_type_id,a.goods_title,a.goods_text,a.goods_img,a.goods_max_price,a.goods_min_price,a.goods_min_market_price,a.id as goods_id"
        $goodsField = "a.id as goods_id,a.goods_title,a.goods_img,a.goods_min_price,a.goods_min_unit,a.goods_min_market_price,a.goods_max_price,a.goods_up_count,a.goods_share_count,a.goods_collect_count,a.goods_read_count,a.goods_sale,a.goods_storage,a.goods_tag";
        $data = $goods_model->goodsSearch($formData, $goodsField);
        return self::returnMsg(1, $data['dataList']);
    }

    /**
     * 获取首页导航分类
     * @param int $type
     * @return \think\response\Json
     */
    public function getLabel($type = 1)
    {
//        $userInfo = $this->currentUser;
        //判断是否会员
//        $is_member = 1;
//        if (isset($userInfo['user_id'])) {
//            $UserModel = new UserModel();
//            $user = $UserModel->getIsMember($userInfo['user_id']);
//            if (isset($user['member_level'])) {
//                $is_member = 2;
//            }
//        }
        if (empty($type)) {
            $type = 1;
        }
        $goods_navbar_model = new GoodsNavbarModel();
//        $field = "a.id,a.name,a.url,a.icon";
        $map = [
            'status' => 0,
            'type' => $type
        ];
        $navbar = $goods_navbar_model->getPageData($map, '', 1, 20);
        $navbar_list = $navbar['dataList'];
        if (intval($type) == 2) {
            $goods_model = new GoodsModel();
            foreach ($navbar_list as &$value) {
                $map = [
                    'goods_status' => 1,
                    'goods_nav_id' => $value['id']
                ];
                $dataList_temp = $goods_model->getPageDataList($map, '', 1, 8);
                $dataList = $dataList_temp['dataList'];
                foreach ($dataList as &$val) {
                    if (mb_strpos($val['goods_tag'], " ") > 0) {
                        $val['goods_tag'] = mb_substr($val['goods_tag'], 0, mb_strpos($val['goods_tag'], " "));
                    }
                }
                $value['goodsList'] = $dataList;
            }
        }
        return self::returnMsg(1, $navbar_list);
    }

    /**
     * 获取县长推荐首页展示列表
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getLeadership()
    {
        $leadership_model = new LeadershipRecModel();
        $map = [
            'status' => 1
        ];
        $leadership = $leadership_model->where($map)->limit(4)->select();
        return self::returnMsg(1, $leadership);
    }

    /**
     * 县长推荐栏目列表
     * @param int $pagenow
     * @param int $limit
     * @return \think\response\Json
     */
    public function getLeadershipList($pagenow = 1, $limit = 10)
    {
        $leadership_model = new LeadershipRecModel();
        $map = [
            'status' => 1
        ];
        $leadership = $leadership_model->getPageData($map, '', $pagenow, $limit);
        return self::returnMsg(1, $leadership);
    }

    /**
     * 县长推荐详情
     * @param string $id
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getLeadershipDetails($id = '')
    {
        $leadership_model = new LeadershipRecModel();
        $map = [
            'id' => $id
        ];
        $data = $leadership_model->where($map)->find();

        $data['goods_ids'] = json_decode($data['goods_ids'], true);
        $goodsModel = new GoodsModel();
        $data['goods_item'] = $goodsModel->getGoodsIdIn(implode(',', $data['goods_ids']), "id,goods_title,goods_img,goods_min_price,goods_min_unit,goods_storage");
        return self::returnMsg(1, $data);
    }

    /**
     * 获取用户协议
     * @param Request $request
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getProtocol(Request $request)
    {
        $type = $request->param('type');
        $user_protocol_model = new UserProtocolModel();
        $data = $user_protocol_model->getProtocol($type);
        return self::returnMsg(1, $data);
    }

    /**
     * 获取导航分类
     * @param string $id (店铺id  店铺首页)
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getStoreLabel($id = '')
    {
        $goods_navbar_model = new GoodsNavbarModel();
        $map = [
            'status' => 0
        ];
        $field = "id,name";
        $navbar = $goods_navbar_model->getList($map, 'sort DESC', $field);
        $goods_model = new GoodsModel();
        $navbar_list = $goods_model->where(['store_id' => $id])->group('goods_nav_id')->field('goods_nav_id')->select();
        $navbar_ids = [];
        foreach ($navbar_list as $value) {
            $navbar_ids[] = $value['goods_nav_id'];
        }
        $out_list = [];
        foreach ($navbar as $value) {
            if (in_array($value['id'], $navbar_ids)) {
                $out_list[] = $value;
            }
        }
        return self::returnMsg(1, $out_list);
    }

    /**
     * 上传文件
     * @param $folder
     * @return \think\response\Json
     */
    public function onUpload($folder = '')
    {
        $rtn = Oss::uploadOssFile($folder);
        return self::returnNormalMsg($rtn);
    }

    /**
     * 删除文件
     * @param $url
     * @return \think\response\Json
     */
    public function onDelfile($url)
    {
        $rtn = Oss::delOssFile($url);
        return self::returnMsg($rtn);
    }

    /**
     * OSS 上传文件临时签名
     * @throws ClientException
     */
    public function onOssSts()
    {
//        用户登录名称 hungeoss@1651337150258100.onaliyun.com
//AccessKey ID LTAI4G78gGkkDhxzeW1mdNpD
//AccessKey Secret HNmMRLPrEU4JRqMzqGWIEO92OmEbMT
//构建一个阿里云客户端，用于发起请求。
//构建阿里云客户端时需要设置AccessKey ID和AccessKey Secret。


//        $accessKeyID = $aliyun_oss['accessKeyId'];
//        $accessKeySecret = $aliyun_oss['accessKeyId'];
//        $roleArn = "hgkjOss";
//        $tokenExpire = 600;
//        $policy = "{
//    \"Statement\": [
//        {
//            \"Action\": \"oss:*\",
//            \"Effect\": \"Allow\",
//            \"Resource\": \"*\"
//        }
//    ],
//    \"Version\": \"1\"
//}";
//
//        $iClientProfile = DefaultProfile::getProfile("cn-beijing", $accessKeyID, $accessKeySecret);
//        $client = new DefaultAcsClient($iClientProfile);
//
//        $request = new RpcAcsRequest();
//        $request->setRoleSessionName("hgOssSessionName");
//        $request->setRoleArn($roleArn);
//        $request->setPolicy($policy);
//        $request->setDurationSeconds($tokenExpire);
//        $response = $client->doAction($request);
//
//        $rows = array();
//        $body = $response->getBody();
//        $content = json_decode($body);
//        if ($response->getStatus() == 200) {
//            $rows['StatusCode'] = 200;
//            $rows['AccessKeyId'] = $content->Credentials->AccessKeyId;
//            $rows['AccessKeySecret'] = $content->Credentials->AccessKeySecret;
//            $rows['Expiration'] = $content->Credentials->Expiration;
//            $rows['SecurityToken'] = $content->Credentials->SecurityToken;
//        } else {
//            $rows['StatusCode'] = 500;
//            $rows['ErrorCode'] = $content->Code;
//            $rows['ErrorMessage'] = $content->Message;
//        }
//        echo json_encode($rows);
//        return;
        $aliyun_oss = [
            'accessKeyId' => 'LTAI4G78gGkkDhxzeW1mdNpD',
            'accessKeySecret' => 'HNmMRLPrEU4JRqMzqGWIEO92OmEbMT'
        ];
        AlibabaCloud::accessKeyClient($aliyun_oss['accessKeyId'], $aliyun_oss['accessKeySecret'])
            ->regionId('cn-beijing')
            ->asDefaultClient();
//设置参数，发起请求。
        try {
            $result = AlibabaCloud::rpc()
                ->product('Sts')
                ->version('2015-04-01')
                ->action('AssumeRole')
                ->method('POST')
                ->host('sts.aliyuncs.com')
                ->options([
                    'query' => [
                        'RegionId' => "cn-beijing",
                        'RoleArn' => "acs:ram::1651337150258100:role/hungeoss",
                        'RoleSessionName' => "hgOssSessionName",
                    ],
                ])
                ->request();
            print_r($result->toArray());
        } catch (ClientException $e) {
            echo $e->getErrorMessage() . PHP_EOL;
        } catch (ServerException $e) {
            echo $e->getErrorMessage() . PHP_EOL;
        }
    }
}
